package com.example.demo.程序员面试金典;

import com.example.demo.leetcode100题.ListNode;

/**
 * @author：zzc
 * @date: 2022/9/8
 */
public class 环路检测 {

    // 就是 判断环形链表 并返回入口节点
    // todo  再做一遍
    // 快慢指针 1，2  环存在 -》1 1

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            ListNode slow = head, fast = head;
            boolean hasCycle = false;
            while (!hasCycle && fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                hasCycle = slow == fast;
            }
            if (!hasCycle) {
                return null;
            }
            ListNode p = head;
            while (p != slow) {
                p = p.next;
                slow = slow.next;
            }
            return p;
        }
    }


}
